import React, {Component} from 'react';
import {
  View,
  Image,
  TouchableOpacity,
  Text,
  ScrollView,
  Platform,
  InteractionManager,
} from 'react-native';

import BaseComponent from '../common/BaseComponent';
import Config from '../../config';
import SizeUtils from '../../common/SizeUtils';
import TImage from '../../components/TImage';
import QuanziTuiJianPage from '../quanzi/QuanziTuiJianPage';
import QuanziFindPage from '../quanzi/QuanziFindPage';
import QuanziGuanZhuPage from '../quanzi/QuanziGuanZhuPage';
import QuanziZonePage from '../quanzi/QuanziZonePage';
import Popover from '../common/Popover';
import PopoverConent from '../common/PopoverConent';

import QZ_Unchecked from '../../actions/quanzi/QZ_Unchecked';


const BTN_LABELS = [{label:"推荐", tag:0,nor:require("../../../resource/images/quanzi/heart_tuijianr.png"),sle:require("../../../resource/images/heart/heart_tuijian.png")},
                    {label:"找圈", tag:1,nor:require("../../../resource/images/quanzi/find.png"),sle:require("../../../resource/images/quanzi/findr.png")},
                    {label:"", tag:2,nor:require("../../../resource/images/heart/heart_tuijian.png"),sle:require("../../../resource/images/quanzi/heart_tuijianr.png")},
                    {label:"关注", tag:3,nor:require("../../../resource/images/quanzi/guanzhur.png"),sle:require("../../../resource/images/quanzi/guanzhu.png")},
                    {label:"我的空间", tag:4,nor:require("../../../resource/images/heart/heart_my.png"),sle:require("../../../resource/images/quanzi/heart_my.png")}];

const topArr=[{name:'审帖',key:'review'},];
const bottomArr=[{name:'发帖',key:'tiezi'},{name:'创建圈子',key:'creat'},];

export default class QuanziMainView extends BaseComponent{
  constructor(props) {
    super(props);
    this._viewPager = null;
    this._noEmpty = false;
    this.state.componentReady = false;
    this.state.currentIndex = 0;
    this.state.updateMark=0;
    this.state.isVisible=false;
    this.state.isBottom=true;
    this.state.buttonRect={};

    this._scrollView = null;
    this._pageWidth = SizeUtils.getWindowSize().width;
    this._pageHeight = SizeUtils.getWindowSize().height- SizeUtils.translateDesignHeightToCode(global.isIphonex?120:100);
  }
  componentDidMount() {
    InteractionManager.runAfterInteractions(()=>{
      this.setState({
        componentReady: true,
      })
      this.initEnterPage();
    })
    
  }
  initEnterPage(){
    this._requestData();
    this._find&&this._find._dealEnterPage();
  }
  _requestData(){
    new QZ_Unchecked().call(this, {board_id:'105',page:1})
  }
  render() {
    if (this.state.componentReady === false) {
      return<View/>
    }
    
    var displayArea = {x: 0, y: 0, width: SizeUtils.getWindowSize().width-10, height: 260};
    return(
      <View style={{backgroundColor:"#00000000"}}>
        {this._renderScrollView()}
        <View style={{height:SizeUtils.translateDesignHeightToCode(global.isIphonex?120:100),
        	borderTopWidth:SizeUtils.translateDesignNumToCode(3),
        	borderColor:"#eeeeee",
          paddingBottom:SizeUtils.translateDesignHeightToCode(global.isIphonex?20:0),
        	flexDirection:"row", justifyContent:"center", alignItems:"center",}}>
        	{this._getButton(0)}
        	{this._getButton(1)}
          {this._getMiddleBtn()}
        	{this._getButton(3)}
        	{this._getButton(4)}
        </View>
        <Popover
            isVisible={this.state.isVisible}
            fromRect={this.state.buttonRect}
            placement={this.state.isBottom?'top':'bottom'}
            isWhite={true}
            arrowSize={{height:10,width:15}}
            displayArea={displayArea}
            onClose={this._closePopover.bind(this)}>
            <View style={{width: 160,height: this.state.isBottom?80:40,backgroundColor:'transparent',}}>
              <PopoverConent titleArr={this.state.isBottom?bottomArr:topArr} popoverPress={this._PopoverPress.bind(this)}/>
            </View>
          </Popover>
      </View>
    )
  }
  _renderScrollView() {
    return(
      <ScrollView style={{width:this._pageWidth,
          height:this._pageHeight}}
        ref={(ref) => this._scrollView = ref}
        horizontal={true}   // 水平方向
        showsHorizontalScrollIndicator={false}  // 水平指示器
        showsVerticalScrollIndicator={false}    // 垂直指示器
        pagingEnabled={true}    // 开启分页功能
        alwaysBounceHorizontal={false} //弹性拉动一截
        onScroll={this._onScroll.bind(this)}
        scrollEnabled={false}
      >
          {this._getPage(0)}
          {this._getPage(1)}
          {this._getPage(2)}
          {this._getPage(3)}
          {this._getPage(4)}
      </ScrollView>
    )
  }
  
  _onScroll(event) {
    // if(this._clickTopBtnTimer) {
    //   return;
    // }
    let x = event.nativeEvent.contentOffset.x;
    let index = Math.round(x / this._pageWidth);
    if(this.state.currentIndex != index) {
      this.setState({
        currentIndex:index,
      })
    }
  }
  _getButton(index) {
    return(
      <TouchableOpacity onPress={()=>this._onPressBtn(index)} style={{width:SizeUtils.getWindowSize().width/5,
          height:SizeUtils.translateDesignHeightToCode(80), flexDirection:"column", justifyContent:"center", alignItems:"center",
          }}>
          <Image source={index == this.state.currentIndex ?BTN_LABELS[index].sle :BTN_LABELS[index].nor} style={{width:25,
            height:25}}/>
        <View style={{height:SizeUtils.translateDesignHeightToCode(index===2?76:36), justifyContent:"center", alignItems:"center",}}>
          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(24), color:index == this.state.currentIndex ? "#db3132": "#666666"}}>
            {BTN_LABELS[index].label}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
  _showPopover(ref) {
      this._popoverbtn.measure((ox, oy, width, height, px, py) => {
         this.setState({
              isBottom:true,
              isVisible: true,
              buttonRect: {x:px, y:Platform.OS !== 'ios'?py:py, width: 80, height: 45}
          });
      });
  }
  _showMoreRightBtn(buttonRect){
    this._popoverbtn.measure((ox, oy, width, height, px, py) => {
         this.setState({
              isBottom:false,
              isVisible: true,
              buttonRect:buttonRect
          });
      });
  }
  _closePopover(){
    this.setState({isVisible: false});
  }
  _PopoverPress(key){
    this._closePopover();
    if ('creat'===key) {
      this.gotoPage(Config.pages.quanzi_create)
    }else if ('review'===key) {
      this.gotoPage(Config.pages.quanzi_review)
    }else if ('tiezi'===key) {
      this.gotoPage(Config.pages.quanzi_write, {});
    }
  }
  _getMiddleBtn() {
    return(
      <TouchableOpacity ref={(ref) => this._popoverbtn = ref} onPress={()=>this._showPopover()} style={{width:SizeUtils.getWindowSize().width/5,
          height:SizeUtils.translateDesignHeightToCode(80), flexDirection:"column", justifyContent:"center", alignItems:"center",
          }}>
          <TImage source={require("../../../resource/images/home/tabbar/changyong_red.png")} 
            style={{ width:35,height:35,}}/>
      </TouchableOpacity>
    )
  }
  _onPressBtn(index) {
    if(this._clickTopBtnTimer) {
      return;
    }
    this._clickTopBtnTimer = setTimeout(() => {
      this._clearClickTopBtnTimer();
    }, 500);
    this._scrollView.scrollTo({x:index * this._pageWidth,animated:false})
  }
  _clearClickTopBtnTimer() {
    this._clickTopBtnTimer && clearTimeout(this._clickTopBtnTimer)
    this._clickTopBtnTimer = null;
  }
  _onPressNavigationBarLeftBtn() {
    this.setState({componentReady:false})
    this.goBack();
  }

  _getPage(index) {
  	if (index==0&&index==this.state.currentIndex) {
  		return(<QuanziTuiJianPage showMoreRightBtn={this._showMoreRightBtn.bind(this)} pageData={this.props.pageData} style={{width:this._pageWidth, height:this._pageHeight}} />);
  	}
  	if (index==1&&index==this.state.currentIndex) {
  		return(<QuanziFindPage ref={(ref) => this._find = ref}  showMoreRightBtn={this._showMoreRightBtn.bind(this)} pageData={this.props.pageData} style={{width:this._pageWidth, height:this._pageHeight}} />);
  	}
    if (index==3&&index==this.state.currentIndex) {
      return(<QuanziGuanZhuPage  showMoreRightBtn={this._showMoreRightBtn.bind(this)} pageData={this.props.pageData} style={{width:this._pageWidth, height:this._pageHeight}} />);
    }
    if (index==4&&index==this.state.currentIndex) {
      return(<QuanziZonePage initEnterPage={this.initEnterPage.bind(this)} pageData={this.props.pageData}  showMoreRightBtn={this._showMoreRightBtn.bind(this)} pageData={this.props.pageData} style={{width:this._pageWidth, height:this._pageHeight}} />);
    }
	return(
		<View style={{width:this._pageWidth, height:this._pageHeight}} />
	)
  }
}